package com.example.demo.grbkxt.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.*;
import com.example.demo.grbkxt.model.User;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@WebFilter("/blog/*")
public class AuthFilter implements Filter {
    private FilterConfig filterConfig;
    private Connection connection; // 添加数据库连接字段

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        System.out.println("AuthFilter initialized");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String requestPath = httpRequest.getRequestURI();
        boolean isLoggedIn = (session != null && session.getAttribute("user") != null);

        if (!isLoggedIn) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
            return;
        }

        // 检查管理员权限
        if (requestPath.contains("/admin")) {
            User user = (User) session.getAttribute("user");
            if (!user.isAdmin()) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/blog/user");
                return;
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        try {
            // 记录过滤器销毁信息
            System.out.println("AuthFilter is being destroyed - 开始清理资源");

            // 关闭数据库连接
            if (connection != null && !connection.isClosed()) {
                connection.close();
                System.out.println("数据库连接已关闭");
            }

            // 清理会话相关资源
            ServletContext context = filterConfig.getServletContext();
            context.log("AuthFilter - 清理完成");

            System.out.println("AuthFilter destroyed successfully - 资源清理完成");
        } catch (SQLException e) {
            System.err.println("关闭数据库连接时出错: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Filter销毁过程中出错: " + e.getMessage());
        }
    }
}
